Skip to main content

use vue-route

Prerequisite

Before Beginning to do use vue-route, some requirement needs:

  1. Install Nodejs, the official website is here, recommend even version like 16.xxx and 18.xxx
  2. Install pnpm by following command, npm install -g pnpm
  3. Create a vite vue3 ts project, using pnpm create vite-app my-vue3-ts-project
  4. Install a editor tool, best recommend is VS-CODE, download from here

Preview Project Structure

Project Construction

Install dependencies

pnpm install vue-router@4.2.5
pnpm install @vitejs/plugin-vue@5.0.2 -D
pnpm install @types/node@20.10.6 -D
pnpm install @vue/tsconfig -D
  1. pnpm install vue-router@4.2.5:

    This command installs the Vue Router package at version 4.2.5.

    Vue Router is a library for Vue.js applications that enables navigation between different components, managing the application's URL, and providing a navigation history.

  2. pnpm install @vitejs/plugin-vue@5.0.2 -D: This command installs the Vite plugin for Vue.js at version 5.0.2.

    Vite is a build tool for modern web development that is particularly optimized for Vue.js. This plugin specifically integrates Vue.js with Vite, allowing you to use Vue components in your Vite projects.

  3. pnpm install @types/node@20.10.6 -D:

    This command installs TypeScript type definitions for Node.js at version 20.10.6.

    When working with TypeScript, having type definitions for the libraries you use is essential for static type checking. The @types/node package provides these definitions for Node.js.

  4. pnpm install @vue/tsconfig -D:

    This command installs the Vue.js TypeScript configuration package.

    The @vue/tsconfig package provides a default TypeScript configuration for Vue.js projects. It includes settings that are commonly used and recommended for Vue.js development. The configuration is typically referenced in the tsconfig.json file of your project with the "extends" property.

Configure tsconfig.json

{
"extends": "@vue/tsconfig/tsconfig.json",
"compilerOptions": {
// this to solve some error hints
"ignoreDeprecations": "5.0",
"sourceMap": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
},
"lib": ["esnext", "dom"]
},

"vueCompilerOptions": {
"nativeTags": ["block", "component", "template", "slot"]
},

"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}

extends: "@vue/tsconfig/tsconfig.json":

  • This line indicates that the current TypeScript configuration extends the settings from the tsconfig.json file provided by the @vue/tsconfig package. It's a way of inheriting a base configuration.

compilerOptions:

  • ignoreDeprecations": "5.0": Specifies that the compiler should ignore deprecation warnings related to TypeScript version 5.0.

  • sourceMap": true: Generates source maps, which are useful for debugging TypeScript code in development environments.

  • baseUrl": ".": Sets the base directory for resolving non-relative module names. In this case, it's set to the current directory.

  • paths: Configures module aliases for easier import statements. For example, @/ is aliased to ./src/, allowing you to write imports like import Foo from '@/components/Foo.vue'.

  • lib: ["esnext", "dom"]: Specifies the libraries that are available at runtime. esnext includes the latest ECMAScript features, and dom includes the DOM types.

vueCompilerOptions:

  • nativeTags: ["block", "component", "template", "slot"]: Specifies which tags should be treated as native Vue.js tags. This is helpful for the Vue.js compiler to recognize certain custom elements in your Vue components.

  • include: ["src//.ts", "src/**/.d.ts", "src//*.tsx", "src//*.vue"]**:

    • Lists the files that should be included in the TypeScript compilation process. In this case, it includes TypeScript files (*.ts, *.d.ts, *.tsx) and Vue files (*.vue) within the src directory and its subdirectories.

Configure vite.config.mts

// vite.config.mts
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import path from 'path';

export default defineConfig({
resolve:{
alias:{
'@': path.resolve(__dirname, 'src')
}
},
plugins: [vue()]
});

export default defineConfig({:

  • Exports the configuration for the Vite project. The configuration is defined using the defineConfig function.

resolve: { alias: { '@': path.resolve(__dirname, 'src') } }:

  • Configures module aliasing for easier import statements. The @ alias is set to point to the src directory, making it convenient to import files using @/ as a prefix. For example, import Foo from '@/components/Foo.vue';.

plugins: [vue()]:

  • Configures the Vite plugins for the project. In this case, it includes the Vue.js plugin initialized with vue(). This enables Vite to handle Vue single-file components during the build process.

Write main.ts

import { createApp } from 'vue'
import App from './App.vue'
import router from './route/index.ts';

createApp(App).use(router).mount('#app')

This code sets up a Vue.js application with a root component (App), uses the Vue Router plugin for navigation, and mounts the entire application to an HTML element with the ID 'app'. This is a common setup for Vue.js single-page applications where routing is managed by Vue Router, and the application is mounted to a specific DOM element.

Write App.vue

<!-- App.vue -->
<template>
<div id="app">
<router-view></router-view>
</div>
</template>

This App.vue component is designed to be the root component of a Vue.js application. It establishes the overall structure of the application by providing a root <div> with the ID "app" and includes a <router-view> element to handle the dynamic rendering of components based on the application's routes. This is a common structure for Vue.js single-page applications that use Vue Router for navigation.

Write route.ts

// router.ts
import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

const routes: RouteRecordRaw[] = [
{
path: '/',
name: 'home',
component: () => import('@/views/MyPage.vue'),
meta: {
title: 'Home',
},
},
]

const router = createRouter({
history: createWebHistory(),
routes,
})

export default router

import { createRouter, createWebHistory } from 'vue-router';:

  • Import the createRouter and createWebHistory functions from the vue-router library. These functions are used to create a Vue Router instance.

import type { RouteRecordRaw } from 'vue-router';:

  • Import the RouteRecordRaw type from the vue-router library. This type is used to define route configurations.

const routes: RouteRecordRaw[] = [...]:

  • Define an array of route configurations. In this example, there is a single route configuration for the home page ('/'). It specifies the name, component, and meta information (in this case, the title) for the route.

const router = createRouter({ history: createWebHistory(), routes });:

  • Use the createRouter function to create a router instance.

  • The history option is set to createWebHistory(), indicating that the router should use the web history API for navigation. This enables cleaner URLs without hash fragments.

  • The routes option is set to the array of route configurations defined earlier.

export default router;:

  • Export the created router instance, making it available for use in other parts of the application.

write MyPage.vue

<template>
<view>
<input type="text" v-model="inputText" />
</view>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
const inputText = ref<string>('hello')
</script>

This create a input text element, and bind the data to inputText variable, inside the script-setup tag , declare ref object with generic string type value of ‘hello’.

Access

Run the project with your script which define in package.json, then visit the url, your will see as below picture;

visited Page

Conclusion

In this user guide, there might be a tendency to make spelling mistakes or encounter issues with commands. It’s advisable to directly copy the commands and paste them into your VS Code terminal. You can download the code from my GitHub Repository

Thank you for your time. If my article helps you, please give it a clap. Also feel free to ask any questions you may have.